package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chuanglan.SMSConst;
import com.chuanglan.sms.util.ChuangLanSmsUtil;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.system.domain.HatchetAgent;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.domain.HatchetSystemUser;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.IHatchetAgentService;
import com.ruoyi.system.service.IHatchetMerchantService;
import com.ruoyi.system.service.IHatchetSystemUserService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Controller
public class SysLoginController extends BaseController
{
	
	@Autowired
	IHatchetSystemUserService systemUserService;
	@Autowired
	ISysUserService sysUserService;
	@Autowired
	IHatchetAgentService agentService;
	@Autowired
	IHatchetMerchantService merchantService;
    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
    	//如果是空卡用户已登录
    	 String ecrlogin = ecrlogin();
    	 if (StringUtils.isNotEmpty(ecrlogin)) {
    		 return ecrlogin;
		}
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
	        return "login";
	    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {	
    	//通过用户账号查询system_user表用户状态
    	HatchetSystemUser systemUser = systemUserService.selectSystemUserByAgentNo(username);
    	if (StringUtils.isNotNull(systemUser)) {
			if ("10B".equals(systemUser.getSTATUS())) {
				 String msg = "用户已被禁用";
				return error(msg);
			}
		}
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(token);
            return success();
        }catch (AuthenticationException e){
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())){
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

 //ecr空卡代还操作逻辑   
    
    @GetMapping("/ecrlogin")
    public String ecrLogin(HttpServletRequest request, HttpServletResponse response)
    {
    	 String ecrlogin = ecrlogin();
    	 if (StringUtils.isNotEmpty(ecrlogin)) {
    		 return ecrlogin;
		}
    	//把所有的商务中心找出来 创建空卡代还账户
    	/*HatchetAgent agent = new HatchetAgent();
    	agent.setTYPE("2");//商务中心
    	agent.setEmployStatus("10A");//启用状态
    	List<HatchetAgent> selectHatchetAgentList = agentService.selectHatchetAgentList(agent);
    	for (HatchetAgent hatchetAgent : selectHatchetAgentList) {
    		
    		SysUser agentUser = sysUserService.selectUserByLoginName(hatchetAgent.getAgentNo());
    		if (StringUtils.isNotNull(agentUser)) {
    			SysUser newUser = new SysUser();
        		newUser.setLoginName("ecr"+ hatchetAgent.getAgentNo());
        		newUser.setPassword(agentUser.getPassword());
        		newUser.setUserName(agentUser.getUserName());
        		newUser.setCreateTime(new Date());
        		newUser.setRemark("ecr");
        		sysUserService.insertUser(newUser);
			}
    		
		}*/
    	
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        return "ecr/html/login";
    }

    @PostMapping("/ecrlogin")
    @ResponseBody
    public Map<String, Object> ecrAjaxLogin(String username, String password)
    {	
    	Map<String, Object> map = new HashMap<>();
    	SysUser selectUserByLoginName = sysUserService.selectUserByLoginName("ecr"+username);
    	if (StringUtils.isNull(selectUserByLoginName)) {
    		map.put("status",BusinessStatus.FAIL);
    		map.put("msg","账号错误");
    		return map;
		}
    	if (!"ecr".equals(selectUserByLoginName.getRemark())) {
    		map.put("status",BusinessStatus.FAIL);
    		map.put("msg","您没有登陆权限");
    		return map;
		}
    	//查询此用户的代理商是否被禁用
		HatchetAgent selectHatchetAgentByNo = agentService.selectHatchetAgentByNo(username);
		if (StringUtils.isNotNull(selectHatchetAgentByNo)) {
			if (!"10A".equals(selectHatchetAgentByNo.getEmployStatus())) {
				map.put("status",BusinessStatus.FAIL);
	    		map.put("msg","您的账户已被禁用，请联系上级");
	    		return map;
			}
		} else {
			map.put("status",BusinessStatus.FAIL);
    		map.put("msg","您的账号不存在");
    		return map;
		}
		
		UsernamePasswordToken token = new UsernamePasswordToken("ecr"+username, password, false);
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(token);
            
        	map.put("status",BusinessStatus.SUCCESS);
    		map.put("msg","登陆成功");
    		return map;
        }catch (AuthenticationException e){
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())){
                msg = e.getMessage();
            }
            map.put("status",BusinessStatus.FAIL);
    		map.put("msg",msg);
    		return map;
        }
    }
    

   
    
    
    
    /**
     * 卡时代H5用户注册
     * @param request
     * @param response
     * @return
     */
     @RequestMapping("/h5Register")
     @ResponseBody
     public Map<String, Object> h5Register(HttpServletRequest request ,HttpServletResponse response,HatchetMerchant merchant)
     {
    	 Map<String, Object> map = new HashMap<String, Object>();
    	 //判断
    	 HatchetMerchant merchant2 = merchantService.selectHatchetMerchantByPhone(merchant.getPHONE());
    	 if (StringUtils.isNotNull(merchant2)) {
    		 map.put("status", BusinessStatus.FAIL);
 			map.put("msg", "该手机号已注册");
 			return map;
		}
    	 if (StringUtils.isEmpty(merchant.getParentPhone())) {
    		 map.put("status", BusinessStatus.FAIL);
  			 map.put("msg", "推荐人手机号不能为空");
  			return map;
		}
    	 //通过推荐人手机号查询推荐人
    	 HatchetMerchant parenMerchant = merchantService.selectHatchetMerchantByPhone(merchant.getParentPhone());
    	 if (StringUtils.isNull(parenMerchant)) {
    		 map.put("status", BusinessStatus.FAIL);
  			 map.put("msg", "推荐人没找到");
  			return map;
		}
    	 //执行用户注册的方法
    	 map = merchantService.h5Register(merchant);
    	 return map;
     }

	// 发送验证码
	@RequestMapping("/h5SendCode")
	@ResponseBody
	public Map<String, Object> sendShortMessage(HttpServletRequest request, HttpServletResponse resp) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取手机号码
		String phone = request.getParameter("phone");
		if (phone == null) {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "获取手机号失败");
			return map;
		}
		//通过手机号查询用户
		 HatchetMerchant merchant2 = merchantService.selectHatchetMerchantByPhone(phone);
    	 if (StringUtils.isNotNull(merchant2)) {
    		 map.put("status", BusinessStatus.FAIL);
 			map.put("msg", "该手机号已注册");
 			return map;
		}
		
		HttpSession session = request.getSession();
		// 校验上次发送短信的时间,判断是否能再次发送短信
		Boolean isSend = checkSendShortMessageOne(phone, session);
		if (!isSend) {// 不能发送
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "一分钟之内不能重复发送验证码");
			return map;
		}
		// 获取四位随机数
		String code = (int) ((Math.random() * 9 + 1) * 1000) + "";// 根据随机数封装短信模板变量
		String params = phone + ",您的注册短信验证码是" + code;
		String eee = ChuangLanSmsUtil.sendSMSVar(SMSConst.zhuce_sms, params);
		if (StringUtils.isNotEmpty(eee)) {
			// 发送成功
			// 短信发送时间
			session.setAttribute(phone + "code", code);
			session.setAttribute(phone + "Time", new Date()); // 保存当前时间
			map.put("status", BusinessStatus.SUCCESS);
			map.put("msg", "发送成功");
			return map;
		} else {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "短信发送失败请重试");
			return map;
		}

	}

	/**
	 * 
	 * @param phone
	 * @param session
	 * @return
	 */
	public boolean checkSendShortMessageOne(String phone,HttpSession session) {
	if(session != null){//根据手机号拿到验证码 
		Date now = new Date();
		Date lastDate =new Date();
		try {
			lastDate = (Date)session.getAttribute(phone + "Time");
		} catch (Exception e) {
			e.printStackTrace();
			return true;
		}
		if (lastDate ==null) {
			return true;
		}
		long diff = now.getTime() - lastDate.getTime();
		if (60000>diff) {
			return false;
		}
	}
	return true;
}
  

    @GetMapping("/unauth")
    public String unauth()
    {
        return "/error/unauth";
    }
}
